package com.wyl.learn02;

import cn.hutool.core.util.RandomUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import com.wyl.config.RabbitMqConfig;

public class Consumer02_1 {

    public static void main(String[] args) throws Exception {
        System.out.println("我是消费者：C1");
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(RabbitMqConfig.IP);
        factory.setUsername(RabbitMqConfig.USERNAME);
        factory.setPassword(RabbitMqConfig.PASSWORD);
        // 这里不能用try-resource，因为执行完会自动关闭。这里要一直监听消息
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        // 设置队列的qos，只允许最多拿2个消息
        channel.basicQos(2);

        System.out.println("C1 等待接收消息处理时间较短");
        //消息消费的时候如何处理消息
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody());
            try {
                Thread.sleep(1 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("接收到消息:" + message);
            /**
             * 1.消息标记 tag
             * 2.是否批量应答未应答消息
             */
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        };
        // 采用手动应答
        channel.basicConsume(Producer02.TASK_QUEUE_NAME_DURABLE, false, deliverCallback, (consumerTag) -> {
            System.out.println(consumerTag + "消费者取消消费接口回调逻辑");
        });
    }
}